angular.module('RDash')
    .directive('rdJsonEditor', [function () {
        return {
            restrict: 'E',
            template: '<div id="jsonEditor"></div>',
            replace: true,
            link: function (scope, ele, attrs) {
                var $container = document.getElementById('jsonEditor');
                var options = {
                    mode: 'code',
                    modes: ['code', 'form', 'text', 'tree', 'view'],
                    onError: function (err) {
                        alert(err.toString());
                    }
                };
                var editor = new JSONEditor($container, options, scope.json);

                scope.getJson = function () {
                    return editor.get();
                };
            }
        };
    }])
    .controller('TJsonEditorCtrl', ['$scope', '$uibModalInstance', 'title', 'json', function ($scope, $uibModalInstance, title, json) {
        $scope.title = title;
        $scope.json = json;

        $scope.save = function () {
            $uibModalInstance.close($scope.getJson());
        };
        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    }]);